package com.boge.parse.ioByte;

import com.boge.parse.base.BaseProtocolEncoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.boge.decoder.AES;
import com.boge.entity.GameOutput;
import com.boge.socket.ActionData;
import com.boge.util.ZlibUtil;

public class IoByteProtocolEncoder extends BaseProtocolEncoder {

	private final AttributeKey CONTEXT = new AttributeKey(getClass(), "context");  
	
	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		GameOutput gameOutput = new GameOutput();
		try {
			ActionData<?> ad = (ActionData<?>) message;
			gameOutput.writeLong(System.currentTimeMillis());// 发送当前服务器的时间
			gameOutput.writeInt(ad.getAction());
			byte[] buf = ad.getBuf();
			buf = buf==null?new byte[0]:buf;
			gameOutput.writeInt(buf.length);
			gameOutput.write(buf, 0, buf.length);
			byte[] bytes = gameOutput.toByteArray();
			// 加密
//			System.out.println(bytes.length);
			String str = getAes(session, CONTEXT).encrypt(bytes);
			gameOutput.reset();
			bytes = str.getBytes();
			// 压缩
			bytes = ZlibUtil.compress(bytes);
//			int len = bytes.length;
//			gameOutput.writeInt(len);
//			gameOutput.write(bytes, 0, len);
			out.write(IoBuffer.wrap(bytes));
		} finally {
			gameOutput.reset();
			gameOutput.close();
		}
	}

	@Override
	public void dispose(IoSession session) throws Exception {
		AES aes = (AES) session.getAttribute(CONTEXT);  
		if (aes != null) {
			session.removeAttribute(CONTEXT);
		}
	}
	
}
